<template>
  <div>
    <el-form inline>
      <el-row>
        <!-- <el-col :span="5">
          <div class="form-item">
            <label class="form-label">起始时间:</label>
            <el-form-item class="form-item-content">
              <el-date-picker   v-selfdbclick
                v-model="startDate"
                type="datetime"
                placeholder="选择日期"
                class="compact-picker"
              ></el-date-picker>
            </el-form-item>
          </div>
        </el-col>

        <el-col :span="5">
          <div class="form-item">
            <label class="form-label">结束时间:</label>
            <el-form-item class="form-item-content">
              <el-date-picker   v-selfdbclick
                v-model="endDate"
                type="datetime"
                placeholder="选择日期"
                class="compact-picker"
              ></el-date-picker>
            </el-form-item>
          </div>
        </el-col>

        <el-col :span="5">
          <div class="form-item">
            <label class="form-label">报警代码:</label>
            <el-form-item class="form-item-content">
              <el-input v-model="errorCode" class="compact-select" placeholder="请输入报警码"></el-input>
            </el-form-item>
          </div>
        </el-col>

        <el-col :span="5">
          <div class="form-item">
            <label class="form-label">TOP数:</label>
            <el-form-item class="form-item-content">
              <el-input v-model="topNumber" class="compact-select" placeholder="请输入TOP数"></el-input>
            </el-form-item>
          </div>
        </el-col>

        <el-col :span="4" class="buttons-row">
          <el-button type="primary"  @click="search">查询</el-button>
          <el-button  @click="exportData">导出数据</el-button>
        </el-col> -->
        <el-form :inline="true">
          <el-form-item label="开始时间">
            <el-date-picker   v-selfdbclick
                v-model="startDate"
                type="datetime"
                placeholder="选择日期"
                class="compact-picker"
              ></el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker   v-selfdbclick
                v-model="endDate"
                type="datetime"
                placeholder="选择日期"
                class="compact-picker"
              ></el-date-picker>
          </el-form-item>
          <el-form-item label="报警代码">
            <el-input v-model="errorCode" class="compact-select" placeholder="请输入报警码"></el-input>
          </el-form-item>
          <el-form-item label="TOP数">
            <el-input v-model="topNumber" class="compact-select" placeholder="请输入TOP数"></el-input>
          </el-form-item>
          <el-form-item>
              <el-button type="primary" @click="search">查询</el-button>
          </el-form-item>
          <el-form-item>
              <el-button type="primary" @click="exportData">导出数据</el-button>
          </el-form-item>
        </el-form>
      </el-row>
    </el-form>

    <!-- Charts Placeholder -->
    <div class="charts" style="margin-top: 5px">
      <div ref="chart1" style="width: 50%; height: 250px;"></div>
      <div ref="chart2" style="width: 50%; height: 250px;"></div>
    </div>

    <div>
      <!-- Table -->
      <el-table :data="tableData" class="table_content"
                :header-cell-style="{'font-weight':'bold', color:'#2A2A2A'}"
                border style="width: 100%; margin-top: 5px" :height="474" :fit="true">
        <el-table-column prop="startTime" label="发生时间" width="180"></el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180"></el-table-column>
        <el-table-column prop="during" label="持续时长 (分钟)" width="80"></el-table-column>
        <el-table-column prop="before" label="设备状态 (报警前)" width="80"></el-table-column>
        <el-table-column prop="after" label="设备状态 (报警后)" width="80"></el-table-column>
        <el-table-column prop="errorCode" label="报警代码" width="80"></el-table-column>
        <el-table-column prop="level" label="报警等级" width="80">
          <template slot="header">
            <el-tooltip placement="top">
              <div slot="content">等级1：提示性报警设备不停机  <br/> 等级2，设备报警宕机</div>
              <div>报警等级</div>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <span>{{ scope.row.level }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="label" label="报警模块" width="80"></el-table-column>
        <el-table-column prop="des" label="报警详情"></el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import {formatDate} from "../../utils/tools";

export default {
  name: 'DeviceRunningStatus',
  data() {
    return {
      startDate: '',
      endDate: '',
      errorCode: '',
      topNumber: '5',
      checkboxValues: [],
      chartCountInstance: null,
      chartTimeInstance: null,
      chartDataByCount: [],
      chartCategoriesByCount: [],
      chartDataByTimes: [],
      chartCategoriesByTimes: [],
      tableData: [],
      query: {
        startTime: "",
        endTime: "",
        errorCode: "",
        topCount: ""
      }
    };
  },
  props: {
    qtCall: {
      type: Object,
      default: null
    }
  },
  methods: {
    search() {
      console.log('查询按钮点击;');
      console.log("startDate: ", formatDate(this.startDate));
      console.log("endDate: ", formatDate(this.endDate));
      console.log("errorCode: ", this.errorCode);
      // 校验起始时间和结束时间
      if (!this.startDate) {
        this.$message.error("请选择起始时间");
        return;
      }
      if (!this.endDate) {
        this.$message.error("请选择结束时间");
        return;
      }
      // 校验起始时间是否早于结束时间
      if (this.startDate > this.endDate) {
        this.$message.error("起始时间不能晚于结束时间");
        return;
      }
      // 校验TOP数
      if (!this.topNumber) {
        this.topNumber = "5";
      }
      console.log("topNumber: ", this.topNumber);

      if (process.env.NODE_ENV === 'production') {
        this.query.startTime = formatDate(this.startDate);
        this.query.endTime = formatDate(this.endDate);
        this.query.errorCode = this.errorCode.toString();
        this.query.topCount = this.topNumber.toString();
        this.qtCall.JsToQt("NeedQueryHistoryRunningStatueInDeviceManagement", this.query);//可以传给qt
        this.fetchData();
      } else {
        this.fetchData();
      }
    },
    fetchData() {
      this.chartDataByCount = []
      this.chartCategoriesByCount = []
      this.chartDataByTimes = []
      this.chartCategoriesByTimes = []

      let chartCountData = [];
      let chartTimeData = [];
      let getTableData = [];
      console.log("刷新柱状图！")
      if (process.env.NODE_ENV === 'production') {
        this.qtCall.QtToJs.connect((func, json) => {
          if (func === "RefreshHistoryRunningStatueInDeviceManagement") {
            const datas = JSON.parse(json)
            if (datas.code === 200) {
              console.log("datas.data[TopRunningErrorsByCount]: ", datas.data["TopRunningErrorsByCount"])
              console.log("datas.data[TopRunningErrorsByTimes]: ", datas.data["TopRunningErrorsByTimes"])
              console.log("datas.data[DeviceLogs]: ", datas.data["DeviceLogs"])
              chartCountData = datas.data["TopRunningErrorsByCount"]
              chartTimeData = datas.data["TopRunningErrorsByTimes"]
              this.tableData = datas.data["DeviceLogs"]
              setTimeout(() => {
                this.fetchChartDataByCount(chartCountData);
                this.fetchChartDataByTimes(chartTimeData);

                this.initChartByCount();
                this.initChartByTimes();
              }, 300)
            }
          }
        })
      } else {
        chartCountData = [
          {
            "label": "ER2854413",
            "value": "500"
          },
          {
            "label": "ER2854413",
            "value": "500"
          },
          {
            "label": "ER2854413",
            "value": "400.00001"
          },
          {
            "label": "ER2854413",
            "value": "500"
          },
          {
            "label": "ER2854413",
            "value": "500"
          }
        ]

        chartTimeData = [
          {
            "label": "ER2854413",
            "value": "500"
          },
          {
            "label": "ER2854413",
            "value": "500"
          },
          {
            "label": "ER2854413",
            "value": "500"
          },
          {
            "label": "ER2854413",
            "value": "500"
          },
          {
            "label": "ER2854413",
            "value": "500"
          }
        ]

        getTableData = [
          {
            "after": "暂停",
            "before": "暂停",
            "des": "详细",
            "during": "0.1s",
            "endTime": "2024-07-26 10:00:00",
            "errorCode": "ER415665",
            "label": "取料气缸",
            "level": "中级",
            "startTime": "2024-07-26 10:00:00"
          },
          {
            "after": "暂停",
            "before": "暂停",
            "des": "详细",
            "during": "0.1s",
            "endTime": "2024-07-26 10:00:00",
            "errorCode": "ER415665",
            "label": "取料气缸",
            "level": "中级",
            "startTime": "2024-07-26 10:00:00"
          },
          {
            "after": "暂停",
            "before": "暂停",
            "des": "详细",
            "during": "0.1s",
            "endTime": "2024-07-26 10:00:00",
            "errorCode": "ER415665",
            "label": "取料气缸",
            "level": "中级",
            "startTime": "2024-07-26 10:00:00"
          },
          {
            "after": "暂停",
            "before": "暂停",
            "des": "详细",
            "during": "0.1s",
            "endTime": "2024-07-26 10:00:00",
            "errorCode": "ER415665",
            "label": "取料气缸",
            "level": "中级",
            "startTime": "2024-07-26 10:00:00"
          },
          {
            "after": "暂停",
            "before": "暂停",
            "des": "详细",
            "during": "0.1s",
            "endTime": "2024-07-26 10:00:00",
            "errorCode": "ER415665",
            "label": "取料气缸",
            "level": "中级",
            "startTime": "2024-07-26 10:00:00"
          },
          {
            "after": "暂停",
            "before": "暂停",
            "des": "详细",
            "during": "0.1s",
            "endTime": "2024-07-26 10:00:00",
            "errorCode": "ER415665",
            "label": "取料气缸",
            "level": "中级",
            "startTime": "2024-07-26 10:00:00"
          },
          {
            "after": "暂停",
            "before": "暂停",
            "des": "详细",
            "during": "0.1s",
            "endTime": "2024-07-26 10:00:00",
            "errorCode": "ER415665",
            "label": "取料气缸",
            "level": "中级",
            "startTime": "2024-07-26 10:00:00"
          },
          {
            "after": "暂停",
            "before": "暂停",
            "des": "详细",
            "during": "0.1s",
            "endTime": "2024-07-26 10:00:00",
            "errorCode": "ER415665",
            "label": "取料气缸",
            "level": "中级",
            "startTime": "2024-07-26 10:00:00"
          },
          {
            "after": "暂停",
            "before": "暂停",
            "des": "详细",
            "during": "0.1s",
            "endTime": "2024-07-26 10:00:00",
            "errorCode": "ER415665",
            "label": "取料气缸",
            "level": "中级",
            "startTime": "2024-07-26 10:00:00"
          },
          {
            "after": "暂停",
            "before": "暂停",
            "des": "详细",
            "during": "0.1s",
            "endTime": "2024-07-26 10:00:00",
            "errorCode": "ER415665",
            "label": "取料气缸",
            "level": "中级",
            "startTime": "2024-07-26 10:00:00"
          },
          {
            "after": "暂停",
            "before": "暂停",
            "des": "详细",
            "during": "0.1s",
            "endTime": "2024-07-26 10:00:00",
            "errorCode": "ER415665",
            "label": "取料气缸",
            "level": "中级",
            "startTime": "2024-07-26 10:00:00"
          },
          {
            "after": "暂停",
            "before": "暂停",
            "des": "详细",
            "during": "0.1s",
            "endTime": "2024-07-26 10:00:00",
            "errorCode": "ER415665",
            "label": "取料气缸",
            "level": "中级",
            "startTime": "2024-07-26 10:00:00"
          },
          {
            "after": "暂停",
            "before": "暂停",
            "des": "详细",
            "during": "0.1s",
            "endTime": "2024-07-26 10:00:00",
            "errorCode": "ER415665",
            "label": "取料气缸",
            "level": "中级",
            "startTime": "2024-07-26 10:00:00"
          },
          {
            "after": "暂停",
            "before": "暂停",
            "des": "详细",
            "during": "0.1s",
            "endTime": "2024-07-26 10:00:00",
            "errorCode": "ER415665",
            "label": "取料气缸",
            "level": "中级",
            "startTime": "2024-07-26 10:00:00"
          },

        ]
        this.tableData = getTableData;
        setTimeout(() => {
          this.fetchChartDataByCount(chartCountData);
          this.fetchChartDataByTimes(chartTimeData);

          this.initChartByCount();
          this.initChartByTimes();
        }, 300)
      }

    },
    fetchChartDataByCount(data_list) {
      this.chartDataByCount = [];
      this.chartCategoriesByCount = [];
      for (let i = 0; i < data_list.length; i++) {
        this.chartDataByCount.push(data_list[i].value);
        this.chartCategoriesByCount.push(data_list[i].label);
      }
    },
    fetchChartDataByTimes(data_list) {
      this.chartDataByTimes = [];
      this.chartCategoriesByTimes = [];
      for (let i = 0; i < data_list.length; i++) {
        this.chartDataByTimes.push(data_list[i].value);
        this.chartCategoriesByTimes.push(data_list[i].label);
      }
    },
    initChartByCount() {
      if (!this.chartDataByCount.length || !this.chartCategoriesByCount.length) return;
      if (!this.chartCountInstance) {
        this.chartCountInstance = echarts.init(this.$refs.chart1);
      }

      const option = {
        title: {
          text: 'TOP报警（按次数）'
        },
        tooltip: {},
        xAxis: {
          data: this.chartCategoriesByCount,
          name: "报警代码"
        },
        yAxis: {
          type: 'value',
          // 确保 Y 轴只显示整数
          axisLabel: {
            formatter: function (value) {
              return Math.floor(value);
            }
          },
          // 防止 Y 轴自动生成小数刻度
          minInterval: 1
        },
        series: [{
          name: '单位：次',
          type: 'bar',
          data: this.chartDataByCount,
          label: {
            show: true,
            position: 'top',
            formatter: '{c}'
          },
        }]
      };
      this.chartCountInstance.setOption(option);
    },
    initChartByTimes() {
      if (!this.chartDataByTimes.length || !this.chartCategoriesByTimes.length) return;
      if (!this.chartTimeInstance) {
        this.chartTimeInstance = echarts.init(this.$refs.chart2);
      }
      const option = {
        title: {
          text: 'TOP报警（按时长，单位：分钟）'
        },
        tooltip: {},
        xAxis: {
          data: this.chartCategoriesByTimes,
          name: "报警代码"
        },
        yAxis: {},
        series: [{
          name: '单位：分钟',
          type: 'bar',
          data: this.chartDataByTimes,
          label: {
            show: true,
            position: 'top',
            formatter: params => {
              return `${parseFloat(params.value).toFixed(2)}`;
            }
          },
        }]
      };
      this.chartTimeInstance.setOption(option);
    },
    exportData() {
      console.log('导出报警码规则文档');
      if (process.env.NODE_ENV === 'production') {
        const data = {
          type: 7,
          startTime: formatDate(this.startDate),
          endTime: formatDate(this.endDate),
          color: this.errorCode.toString(),
          topCount: this.topNumber.toString()
        }
        this.qtCall.JsToQt("NeedExport", data);
      }
    }
  }
};
</script>

<style scoped>
.form-row {
  display: flex;
  justify-content: space-between;
}

.buttons-row {
  display: flex;
  justify-content: flex-end;
  padding-right: 10px;
  margin-top: 5px;
}

/deep/ .compact-picker .el-input__inner,
/deep/ .compact-select .el-input__inner {
  /* height: 30px;
  width: 220px;
  margin-top: 5px; */
}

.form-item {
}

.form-label {
  vertical-align: middle;
  width: 70px;
  line-height: 40px;
  padding-right: 5px;
  height: 45px;
  font-weight:bold;
  color:#2A2A2A
}

.el-checkbox-group .el-checkbox {
  margin-right: 10px; /* 调整多选框之间的间距 */
}

.charts {
  display: flex;
  justify-content: space-between;
}


</style>
